//
//  StatusPictureCollectionView.swift
//  weibo1
//
//  Created by changhongliang on 2017/8/1.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit
import SDWebImage

class StatusPictureCollectionView: UICollectionView {
    var statusViewModel: StatusViewModel?
//    {
//        didSet{
//            // 6.1计算配图和配图容器的尺寸
//            let (itemSize, size) = caculateSize()
//            // 6.2设置配图容器的尺寸
//            self.frame.size = size
////            self.contentSize = size
////            pictureCollectionVeiwWidthCons.constant = size.width
////            pictureCollectionViewHeightCons.constant = size.height
//            // 6.3设置配图的尺寸
//            if itemSize != CGSize.zero
//            {
//                (collectionViewLayout as! UICollectionViewFlowLayout).itemSize = itemSize
//            }
//            
//            // 6.4刷新表格
//            reloadData()
//        }
//    }

    
    //MARK:- 内部控制方法
    /// 计算配图的尺寸
    /// 第一个参数: imageView的尺寸
    /// 第二个参数: 配图容器的尺寸
    /*
     没有配图 :不显示CGSizeZero
     一张配图: 图片的尺寸就是配图和配图容器的尺寸
     四张配图: 田字格
     其他配图: 九宫格
     */
    
    func caculateSize()->(CGSize,CGSize)
    {
        // 1.获取配图个数
        let count = statusViewModel?.thumbnail_pics?.count ?? 0
        //2.1 判断有没有配图
        if count == 0 {
            return (CGSize.zero,CGSize.zero)
        }
        //2.2 判断是否是一张配图
        if count == 1 {
//            let urlStr = statusViewModel?.thumbnail_pics!.last?.absoluteString
//            let image = SDWebImageManager.shared().imageCache?.imageFromCache(forKey: urlStr ?? "")
//            HLLog("1size:\(image!.size)")
//            HLLog("2size:\(image!.size)")
//            return (image!.size, image!.size)
            return(CGSize(width: 90, height: 90),CGSize(width: 90, height: 90))
        }
        
        let imageWidth:CGFloat = 90
        let imageHeight:CGFloat = imageWidth
        let imageMargin:CGFloat = 10
        
        //判断是否是4张配图
        if count == 4 {
            let col:CGFloat = 2
            //计算宽度 宽度 = 列数 *图片宽度 +(列数 - 1)*间隙
            let width = col * imageWidth + (col - 1) * imageMargin
            //计算高度
            let height = width
            return (CGSize(width: 90, height: 90),CGSize(width: width, height: height))
        }
        
        //其他配图 九宫格
        
        let col:CGFloat = 3
        let row = (count - 1 )/3 + 1
        let width = col * imageWidth + (col - 1) * imageMargin
        let height = CGFloat (row) * imageHeight + CGFloat(row - 1) * imageMargin
        return (CGSize(width: 90, height: 90),CGSize(width: width, height: height))
        
    }
    
   
 



}


extension  StatusCell:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return statusViewModel?.thumbnail_pics?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StatusPictureCollectionViewCellID, for: indexPath) as! StatusPictureCollectionViewCell
        let url = statusViewModel?.thumbnail_pics![indexPath.item]
        cell.imageURL = url as URL?
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let url = statusViewModel?.bmiddle_pics?[indexPath.item] else {
            return
        }
        let cell = collectionView.cellForItem(at: indexPath) as! StatusPictureCollectionViewCell
        
        //下载图片
        SDWebImageManager.shared().imageDownloader?.downloadImage(with: url as URL, options: SDWebImageDownloaderOptions(rawValue: 0), progress: { (current, total, _) in
            DispatchQueue.main.async { // 2
                cell.imageView?.progress =  CGFloat(current) / CGFloat(total) // 3
            }

        }, completed: { (_, _, error, _) in
            //发送通知,通知控制器弹出图片浏览器,并且传递当前collectionview所有的配图以及被点击的索引
            NotificationCenter.default.post(name:NSNotification.Name(rawValue: HLPhotoBrowserShow), object: self, userInfo: ["urls":self.statusViewModel?.bmiddle_pics ?? [NSURL]() ,"indexPath":indexPath])
        
        })
        
      
    }
    
    
}

class StatusPictureCollectionViewCell: UICollectionViewCell {
    var  imageView: ProgressImageView?
    var  gifImageView: UIImageView?
    //
    //配图对应的URL
    var imageURL:URL?
    {
        didSet{
            imageView?.sd_setImage(with: imageURL!)
            guard let urlStirng = imageURL?.absoluteString else {
                return
            }
            gifImageView?.isHidden = (urlStirng as NSString).pathExtension != "gif"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子控件
        imageView = ProgressImageView()
        self.contentView.addSubview(imageView!)
        imageView?.frame = self.bounds
    
        
        gifImageView = UIImageView(image: UIImage(named:"gif"))
        self.contentView.addSubview(gifImageView!)
        gifImageView?.snp.makeConstraints({ (make) in
            make.trailing.equalTo(self.contentView.snp.trailing)
            make.bottom.equalTo(self.contentView.snp.bottom)
        })
        gifImageView?.sizeToFit()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
}

//class StatusPictureLayout: UICollectionViewFlowLayout {
//    override func prepare() {
//        super.prepare()
//        //1.计算宽度
//        let width = UIScreen.main.bounds.width / 4
//        itemSize  = CGSize(width: width, height: width)
//        minimumInteritemSpacing = 0
//        minimumLineSpacing = 0
//        scrollDirection = UICollectionViewScrollDirection.vertical
//        collectionView?.showsVerticalScrollIndicator = false
//        collectionView?.showsHorizontalScrollIndicator = false
//    }
//    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
//        return true
//    }
//    
//    
//}


